package com.yzdbx.individualtask;

import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

public class PurchaseReGen {
    /**
     * 采购订单、采购明细
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // 处理日期参数
        String startDate = "2025-07-01";
        String endDate = "2025-07-10";
        
        if (args.length >= 2) {
            startDate = args[0];
            endDate = args[1];
            System.out.println("指定生成日期范围: " + startDate + " 到 " + endDate);
        } else if (args.length == 1) {
            startDate = args[0];
            endDate = args[0];
            System.out.println("指定生成日期: " + startDate);
        } else {
            System.out.println("未指定日期，将生成指定数量的采购订单数据");
        }
        
        // 初始化 GenUtil 的日期信息
        LocalDate currentDate = LocalDate.now();
        if (startDate != null) {
            currentDate = LocalDate.parse(startDate);
        }
        GenUtil.setCurDate(currentDate);
        GenUtil.setCurTimeStamp(new Timestamp(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()));
        
        Connection connection = DbUtil.getConnection();
        boolean originalAutoCommit = true;
        
        try {
            originalAutoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);

            // 查询供应商信息
            List<Integer> supplierIds = new ArrayList<>();
            try (PreparedStatement statement = connection.prepareStatement("select id from supplyManagement");
                 ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    supplierIds.add(resultSet.getInt("ID"));
                }
            }

            // 查询产品信息（原材料）
            List<Integer> productIds = new ArrayList<>();
            try (PreparedStatement statement = connection.prepareStatement("select id from gy02ProductRepository where productClassification in ('原材料')");
                 ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    productIds.add(resultSet.getInt("ID"));
                }
            }

            // 查询用户信息
            List<String> userIds = new ArrayList<>();
            try (PreparedStatement statement = connection.prepareStatement("select memberId as ID from corp_member");
                 ResultSet resultSet = statement.executeQuery()) {
                while (resultSet.next()) {
                    userIds.add(resultSet.getString("ID"));
                }
            }

            if (supplierIds.isEmpty()) {
                System.out.println("没有找到供应商数据，无法生成采购订单！");
                return;
            }
            if (productIds.isEmpty()) {
                System.out.println("没有找到原材料产品数据，无法生成采购订单！");
                return;
            }
            if (userIds.isEmpty()) {
                System.out.println("没有找到用户数据，无法生成采购订单！");
                return;
            }

            System.out.println("找到 " + supplierIds.size() + " 个供应商，" + productIds.size() + " 个原材料产品，" + userIds.size() + " 个用户");

            // 确定生成数量
            int count = 0;
            if (startDate != null && endDate != null) {
                // 根据日期范围确定生成数量
                LocalDate start = LocalDate.parse(startDate);
                LocalDate end = LocalDate.parse(endDate);
                long days = java.time.temporal.ChronoUnit.DAYS.between(start, end) + 1;
                count = (int) (days * RandomUtil.randomInt(2, 5)); // 每天2-5个采购订单
            } else {
                // 默认生成数量
                count = RandomUtil.randomInt(10, 20);
            }
            
            System.out.println("准备生成 " + count + " 个采购订单");

            int maxOrderId = getMaxId(connection, "cgPurchaseOrderForms");
            int maxDetailId = getMaxId(connection, "breakdownOfPurchaseOrders");

            // 准备批量插入语句
            String detailSql = "insert into breakdownOfPurchaseOrders (id,procurementInformation,procurementVolume,unitPrice,numberOfShipmentsArrived,numberOfRefunds,associatedPurchaseOrders,f739,f12e) values (?,?,?,?,?,?,?,?,?)";
            String purchaseSql = "insert into cgPurchaseOrderForms (id,purchaseOrderNumber,chiefProcurementOfficer,dateOfProcurement,associatedSuppliers,auditStatus,procurementVolume,amountProcured,numberOfShipmentsArrived,amountOfGoodsToBeDelivered,synchronisingFolderFailedSS,created) values (?,?,?,?,?,?,?,?,?,?,?,?)";

            try (PreparedStatement detailStatement = connection.prepareStatement(detailSql);
                 PreparedStatement purchaseStatement = connection.prepareStatement(purchaseSql)) {

                int batchCount = 0;
                final int BATCH_SIZE = 3;
                
                // 按日期分组的采购订单号计数器
                Map<String, Integer> dateCounterMap = new HashMap<>();

                for (int i = 1; i <= count; i++) {
                    int orderCount = 0;
                    BigDecimal totalPrice = BigDecimal.ZERO;
                    int curOrderId = ++maxOrderId;

                    // 确定订单日期
                    LocalDate orderDate;
                    if (startDate != null && endDate != null) {
                        LocalDate start = LocalDate.parse(startDate);
                        LocalDate end = LocalDate.parse(endDate);
                        long days = java.time.temporal.ChronoUnit.DAYS.between(start, end);
                        long randomDays = RandomUtil.randomLong(0, days + 1);
                        orderDate = start.plusDays(randomDays);
                    } else {
                        orderDate = currentDate;
                    }
                    
                    // 设置当前日期为订单日期，确保订单号生成正确
                    GenUtil.setCurDate(orderDate);
                    GenUtil.setCurTimeStamp(new Timestamp(orderDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()));
                    
                    // 按日期分组的采购订单号生成逻辑
                    String dateKey = orderDate.toString();
                    int currentCount = dateCounterMap.getOrDefault(dateKey, 0) + 1;
                    dateCounterMap.put(dateKey, currentCount);
                    
                    // 生成采购订单号
                    String purchaseOrderNumber = GenUtil.getNo("CGDD", currentCount);
                    System.out.println("正在处理第 " + i + " 个采购订单，订单号: " + purchaseOrderNumber + ", 日期: " + orderDate);

                    // 生成采购订单明细
                    int detailCount = RandomUtil.randomInt(1, 4);
                    List<Integer> proIds = new ArrayList<>();

                    for (int j = 1; j <= detailCount; j++) {
                        int curDetailId = ++maxDetailId;
                        detailStatement.setInt(1, curDetailId);
                        detailStatement.setInt(2, GenUtil.getNoRepeatId(RandomUtil.randomEle(productIds), proIds, productIds));
                        int number = RandomUtil.randomInt(2, 3000);
                        detailStatement.setInt(3, number);
                        BigDecimal unitPrice = RandomUtil.randomBigDecimal(BigDecimal.ONE, BigDecimal.valueOf(20)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        detailStatement.setBigDecimal(4, unitPrice);
                        detailStatement.setInt(5, number);
                        detailStatement.setInt(6, 0);
                        detailStatement.setInt(7, curOrderId);
                        detailStatement.setTimestamp(8, GenUtil.CUR_TIME_STAMP.get());
                        detailStatement.setString(9, RandomUtil.randomEle(userIds));
                        orderCount += number;
                        totalPrice = totalPrice.add(unitPrice.multiply(BigDecimal.valueOf(number)));
                        detailStatement.addBatch();
                    }

                    // 设置采购订单信息
                    String userId = RandomUtil.randomEle(userIds);
                    purchaseStatement.setInt(1, curOrderId);
                    purchaseStatement.setString(2, purchaseOrderNumber);
                    purchaseStatement.setString(3, userId);
                    purchaseStatement.setDate(4, java.sql.Date.valueOf(orderDate));
                    purchaseStatement.setInt(5, RandomUtil.randomEle(supplierIds));
                    purchaseStatement.setString(6, "已通过");
                    purchaseStatement.setInt(7, orderCount);
                    purchaseStatement.setBigDecimal(8, totalPrice);
                    purchaseStatement.setInt(9, orderCount);
                    purchaseStatement.setBigDecimal(10, totalPrice);
                    purchaseStatement.setString(11, userId);
                    purchaseStatement.setTimestamp(12, GenUtil.CUR_TIME_STAMP.get());
                    purchaseStatement.addBatch();

                    batchCount++;
                    // 每BATCH_SIZE条记录执行一次批量插入
                    if (batchCount >= BATCH_SIZE) {
                        detailStatement.executeBatch();
                        purchaseStatement.executeBatch();
                        connection.commit();
                        batchCount = 0;
                    }
                }

                // 执行剩余的批量插入
                if (batchCount > 0) {
                    detailStatement.executeBatch();
                    purchaseStatement.executeBatch();
                    connection.commit();
                }

            }

            if (startDate != null && endDate != null) {
                if (startDate.equals(endDate)) {
                    System.out.println(startDate + " 日期的采购订单数据生成完成！共生成 " + count + " 条采购订单记录");
                } else {
                    System.out.println(startDate + " 到 " + endDate + " 日期范围的采购订单数据生成完成！共生成 " + count + " 条采购订单记录");
                }
            } else {
                System.out.println("采购订单数据生成完成！共生成 " + count + " 条采购订单记录");
            }
            
        } finally {
            try {
                connection.setAutoCommit(originalAutoCommit);
            } catch (SQLException ignore) {}
            DbUtil.closeConnection(connection);
        }
    }

    private static int getMaxId(Connection connection, String table) throws SQLException {
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT MAX(id) FROM " + table)) {
            if (rs.next()) {
                return rs.getInt(1);
            }
        }
        return 0;
    }
} 